package com.example.booklist.interceptor;

import com.example.booklist.constant.UserConstant;
import com.example.booklist.model.Result;
import com.example.booklist.model.UserInfo;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("LoginInterceptor ⽬标⽅法执⾏前执⾏..");
        HttpSession session = request.getSession(false);
        if(session != null) {
            UserInfo userInfo = (UserInfo)session.getAttribute(UserConstant.SESSION_USER_KEY);
            if(userInfo != null) {
                return true;
            }
        }
        response.setStatus(401);//未登录状态
        return false;

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("LoginInterceptor ⽬标⽅法执⾏后执⾏..");
        return;
    }
}
